<template>
  <el-row style="margin-left: 10px">
    <el-col>
      <el-card style="border-radius: 10px">
        <template
          #header
          type="flex"
          justify="space-between"
          style="align-items: center"
        >
          <el-row
            type="flex"
            justify="space-between"
            style="align-items: center"
          >
            <div class="clearfix" style="text-align: left; display: flex">
              药品列表
            </div>
            <div style="text-align: right; display: flex">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入药品名称"
                style="width: 300px; margin-right: 10px"
              >
                <template #prefix>
                  <el-icon class="el-input__icon">
                    <search />
                  </el-icon>
                </template>
              </el-input>
              <el-select
                v-model="searchForm.drugType"
                placeholder="请选择药品类型"
              >
                <template #prefix>
                  <el-icon class="el-select__icon">
                    <aim />
                  </el-icon>
                </template>
                <el-option
                  v-for="item in drugTypes"
                  :key="item.id"
                  :label="item.value"
                  :value="item.key"
                >
                </el-option>
              </el-select>
              <el-button
                @click="reset"
                type="info"
                plain
                style="margin-left: 10px"
                >重置</el-button
              >
              <el-button @click="search" type="success" plain>查询</el-button>
              <el-button
                type="primary"
                @click="addDrug"
                style="
                  background: -webkit-linear-gradient(
                    right,
                    #0080ff,
                    #0080ff80
                  );
                "
              >
                新建药品
              </el-button>
            </div>
          </el-row>
        </template>
        <el-table
          :data="
            drugs.slice(
              (pagination.currentpage - 1) * pagination.pagesize,
              pagination.currentpage * pagination.pagesize
            )
          "
          stripe
          style="width: 100%"
          v-loading="loading"
          element-loading-text="玩命加载中，请您耐心等待~"
        >
          <el-table-column
            v-for="(value, key, index) in drugLable"
            :key="index"
            :prop="key"
            :label="value"
            sortable
            align="center"
            :fixed="index == 0 ? true : false"
            min-width="125px"
            :formatter="formatterproportion"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            min-width="125px"
            style="
              background: -webkit-linear-gradient(right, #0080ff, #0080ff80)
                no-repeat;
            "
          >
            <template v-slot="scope">
              <el-dropdown
                trigger="click"
                @command="handleCommand(scope.row, $event)"
              >
                <el-button
                  type="primary"
                  style="
                    background: -webkit-linear-gradient(
                        right,
                        #0080ff,
                        #0080ff80
                      )
                      no-repeat;
                  "
                >
                  操 作<el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="a">
                      <i class="el-icon-edit"></i>
                      <span>修改</span>
                    </el-dropdown-item>
                    <el-dropdown-item command="b">
                      <i class="el-icon-delete"></i>
                      <span>删除</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :page-size="pagination.pagesize"
          v-model:currentPage="pagination.currentpage"
          layout="prev, pager, next"
          :total="pagination.total"
          @current-change="handleCurrentChange"
          style="display: flex; justify-content: center"
        >
        </el-pagination>
      </el-card>
    </el-col>

    <el-dialog
      title="修改药品信息"
      v-model="dialogVisible2"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form
        :model="drugForm"
        label-position="left"
        :rules="rules"
        ref="drugForm"
      >
        <el-form-item prop="name">
          <el-row style="text-align: left">请输入药品名称</el-row>
          <el-input v-model="drugForm.name"></el-input>
        </el-form-item>
        <el-form-item prop="specification">
          <el-row style="text-align: left">请输入药品规格</el-row>
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="drugForm.specification"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="manufacturer">
          <el-row style="text-align: left">请输入生产厂家</el-row>
          <el-input v-model="drugForm.manufacturer"></el-input>
        </el-form-item>
        <el-form-item prop="usageDosage">
          <el-row style="text-align: left">请输入用法用量</el-row>
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="drugForm.usageDosage"
          >
          </el-input>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item prop="unit" style="width: 100%">
              <el-row style="text-align: left">请选择单位</el-row>
              <el-row>
                <el-select
                  style="width: 100%"
                  v-model="drugForm.unit"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in units"
                    :key="item.id"
                    :label="item.value"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="drugType" style="width: 100%">
              <el-row style="text-align: left">请选择药品类型</el-row>
              <el-row>
                <el-select
                  style="width: 100%"
                  v-model="drugForm.drugType"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in drugTypes"
                    :key="item.id"
                    :label="item.value"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="price">
              <el-row style="text-align: left">请输入单价</el-row>
              <el-input-number
                :min="10"
                :max="100000"
                :step="0.01"
                step-strictly
                :precision="2"
                v-model="drugForm.price"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="inventory">
              <el-row style="text-align: left">请输入库存</el-row>
              <el-input-number
                :min="1"
                :max="10000000"
                :step="1"
                step-strictly
                v-model="drugForm.inventory"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button plain @click="handleClose('drugForm')">取消</el-button>
        <el-button type="info" plain @click="resetForm('drugForm')"
          >重置</el-button
        >
        <el-button type="primary" plain @click="confirmUpdate('drugForm')"
          >提交</el-button
        >
      </template>
    </el-dialog>
    <el-dialog
      title="新建药品"
      v-model="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form
        :model="drugForm"
        label-position="left"
        :rules="rules"
        ref="drugForm"
      >
        <el-form-item prop="name">
          <el-row style="text-align: left">请输入药品名称</el-row>
          <el-input v-model="drugForm.name"></el-input>
        </el-form-item>
        <el-form-item prop="specification">
          <el-row style="text-align: left">请输入药品规格</el-row>
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="drugForm.specification"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="manufacturer">
          <el-row style="text-align: left">请输入生产厂家</el-row>
          <el-input v-model="drugForm.manufacturer"></el-input>
        </el-form-item>
        <el-form-item prop="usageDosage">
          <el-row style="text-align: left">请输入用法用量</el-row>
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="drugForm.usageDosage"
          >
          </el-input>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item prop="unit" style="width: 100%">
              <el-row style="text-align: left">请选择单位</el-row>
              <el-row>
                <el-select
                  style="width: 100%"
                  v-model="drugForm.unit"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in units"
                    :key="item.id"
                    :label="item.value"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="drugType" style="width: 100%">
              <el-row style="text-align: left">请选择药品类型</el-row>
              <el-row>
                <el-select
                  style="width: 100%"
                  v-model="drugForm.drugType"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in drugTypes"
                    :key="item.id"
                    :label="item.value"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="price">
              <el-row style="text-align: left">请输入单价</el-row>
              <el-input-number
                :min="10"
                :max="100000"
                :step="0.01"
                step-strictly
                :precision="2"
                v-model="drugForm.price"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="inventory">
              <el-row style="text-align: left">请输入库存</el-row>
              <el-input-number
                :min="0"
                :max="10000000"
                :step="1"
                step-strictly
                :precision="2"
                v-model="drugForm.inventory"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button plain @click="handleClose('drugForm')">取 消</el-button>
        <el-button type="info" plain @click="resetForm('drugForm')"
          >重 置</el-button
        >
        <el-button type="primary" plain @click="postForm('drugForm')"
          >提 交</el-button
        >
      </template>
    </el-dialog>
  </el-row>
</template>

<script>
import { deleteDrugAPI } from "@/api/pharmacy/deleteDrugAPI";
import { getDrugListAPI } from "@/api/pharmacy/getDrugListAPI";
import { addDrugAPI } from "@/api/pharmacy/addDrugAPI";
import { updateDrugAPI } from "@/api/pharmacy/updateDrugAPI";
export default {
  // 配置式API、组合式API
  data() {
    return {
      // 表格加载
      loading: false,
      // 新建页可见性
      dialogVisible: false,
      dialogVisible2: false,
      // 药品列表
      drugs: [],
      drugLable: {
        id: "药品编号",
        name: "药品名称",
        specification: "药品规格",
        manufacturer: "生产厂家",
        usageDosage: "用法用量",
        unit: "单位",
        price: "单价（元）",
        drugType: "药品类型",
        inventory: "库存",
        // deleted:
        gmtCreate: "创建时间",
        gmtModify: "修改时间",
      },

      // 查询表单
      searchForm: {
        name: "",
        drugType: "",
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: "请输入药品名称", trigger: "blur" }],
        specification: [
          { required: true, message: "请输入药品规格", trigger: "blur" },
        ],
        manufacturer: [
          { required: true, message: "请输入生产厂家", trigger: "blur" },
        ],
        usageDosage: [
          { required: true, message: "请输入用法用量", trigger: "blur" },
        ],
        unit: [{ required: true, message: "请选择单位", trigger: "blur" }],
        price: [
          { required: true, message: "请输入单价", trigger: "blur" },
          {
            type: "number",
            min: 10,
            max: 100000,
            message: "单价必须在十至十万之间！",
            trigger: "blur",
          },
        ],
        drugType: [
          { required: true, message: "请选择药品类型", trigger: "blur" },
        ],
        inventory: [
          { required: true, message: "请输入库存", trigger: "blur" },
          {
            type: "number",
            min: 0,
            max: 10000000,
            message: "库存必须在零至一千万之间！",
            trigger: "blur",
          },
        ],
      },
      // 分页器控制参数
      pagination: {
        pagesize: 5,
        currentpage: 1,
        total: 2,
      },
      // 新建/修改药品表单
      drugForm: {
        id: "",
        name: "",
        specification: "",
        manufacturer: "",
        usageDosage: "",
        unit: "",
        price: 0,
        drugType: "",
        inventory: 0,
        deleted: false,
        gmtCreate: "",
        gmtModify: "",
      },
    };
  },
  computed: {
    drugTypes() {
      let list = [];
      const codeNames = this.$store.state.pharmacyOptions.codeNames;
      for (let i = 0; i < codeNames.length; i++) {
        if (codeNames[i].type == "drugType") {
          list.push(codeNames[i]);
        }
      }
      return list;
    },

    units() {
      let list = [];
      const codeNames = this.$store.state.pharmacyOptions.codeNames;
      for (let i = 0; i < codeNames.length; i++) {
        if (codeNames[i].type == "unit") {
          list.push(codeNames[i]);
        }
      }

      return list;
    },
  },
  methods: {
    reset() {
      this.searchForm.name = "";
      this.searchForm.drugType = "";
      this.getDrugList(this.searchForm);
    },

    search() {
      if (this.searchForm.name == "" && this.searchForm.drugType == "") {
        this.$message.warning("查询条件不能全部为空！");
        return false;
      }
      this.getDrugList(this.searchForm);
    },
    // 分页器切换页面
    handleCurrentChange(currentPage) {
      this.pagination.currentpage = currentPage;
    },
    // 格式化表格
    formatterproportion(row, column) {
      if (column.property == "gmtCreate" || column.property == "gmtModify") {
        return this.$filters.dateFormat(row[column.property]);
      } else if (column.property == "unit") {
        //  调用药品规格过滤器
        return this.$filters.unitFormat(row[column.property]);
      } else if (column.property == "drugType") {
        // 调用药品类型过滤器
        return this.$filters.drugTypeFormat(row[column.property]);
      } else if (column.property == "payStatus") {
        // 调用缴费状态过滤器
        return this.$filters.payStatusFormat(row[column.property]);
      } else if (column.property == "deliveryStatus") {
        // 调用发放状态过滤器
        return this.$filters.deliveryStatusFormat(row[column.property]);
      }
      return row[column.property];
    },
    // 下拉框触发函数
    handleCommand(item, command) {
      if (command == "a") {
        this.$message.success("修改操作");
        this.drugForm.id = item.id;
        this.drugForm.name = item.name;
        this.drugForm.specification = item.specification;
        this.drugForm.manufacturer = item.manufacturer;
        this.drugForm.usageDosage = item.usageDosage;
        this.drugForm.unit = item.unit;
        this.drugForm.price = item.price;
        this.drugForm.drugType = item.drugType;
        this.drugForm.inventory = item.inventory;
        this.drugForm.deleted = item.deleted;
        this.drugForm.gmtCreate = item.gmtCreate;
        this.drugForm.gmtModify = item.gmtModify;
        this.dialogVisible2 = true;
      } else if (command == "b") {
        this.$confirm("确认删除？")
          .then(() => {
            this.deleteDrug(item.id);
            setTimeout(() => {
              this.reset();
            }, 500);
          })
          .catch(() => {
            this.$message.info("操作取消");
          });
      }
    },

    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 关闭表单
    handleClose(formName) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.dialogVisible = false;
          this.dialogVisible2 = false;
          this.resetForm(formName);
        })
        .catch((_) => {});
    },
    confirmUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const confirm = this.$confirm("确认修改药品吗？", "提交表单")
            .then(async () => {
              const { data: res } = await updateDrugAPI(this.drugForm);

              if (res.statusCode == "C200") {
                this.$message.success(res.msgId);
                this.resetForm(formName);
                this.reset();
                this.dialogVisible2 = false;
              } else this.$message.error(res.msgId);
            })
            .catch(() => {
              this.$message.info("操作取消");
            });
        }
      });
    },
    //确认新建药品
    postForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const confirm = this.$confirm("确认新建药品吗？", "提交表单")
            .then(async () => {
              const { data: res } = await addDrugAPI(this.drugForm);
              if (res.statusCode == "C200") {
                this.$message.success(res.msgId);

                this.resetForm(formName);
                this.reset();
                this.dialogVisible = false;
              } else this.$message.error(res.msgId);
            })
            .catch(() => {
              this.$message.info("操作取消");
            });
        }
      });
    },
    beforeclose(formName) {
      this.dialogVisible = false;
      this.dialogVisible2 = false;
      if (typeof formName == String) this.resetForm(formName);
    },
    // 打开表单
    addDrug() {
      this.dialogVisible = true;
      this.$message.success("打开表单");
    },

    async deleteDrug(id) {
      const { data: res } = await deleteDrugAPI(id);
      if (res.statusCode == "C200") {
        this.$message.success(res.msgId);
      } else {
        this.$message.error(res.msgId);
      }
    },

    // 获取药品列表
    async getDrugList(searchForm) {
      this.loading = true;
      const { data: res } = await getDrugListAPI(searchForm);
      if (res.statusCode == "C200") {
        this.$message.success(res.msgId);
        this.drugs = res.result;
        this.pagination.total = this.drugs.length;
      } else {
        this.$message.error(res.msgId);
      }
      this.loading = false;
    },
  },

  created() {
  
    this.getDrugList(this.searchForm);
    
  },
};
</script>

<style></style>
